package com.controller.supply;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.common.DesUtils;
import com.common.db.RedisUtils;
import com.common.easyui.EasyuiUtils;
import com.common.easyui.JsonTreeData;
import com.common.http.HttpResult;
import com.common.http.HttpStatus;
import com.common.model.Global;
import com.common.model.UserTypeEnum;
import com.common.spring.SpringMvcUtils;
import com.controller.task.SurpviseController;
import com.dao.supply.ModuleDao;
import com.dao.supply.UserMapper;
import com.dao.sys.SysManageMapper;
import com.dao.sys.SysModuleMapper;
import com.enums.SysModuleIdEnum;
import com.model.supply.ModuleModel;
import com.model.supply.SupplyUserModel;
import com.model.sys.LoginModel;
import com.model.sys.SysModule;
import com.service.supply.LoginService;

/**
 * 供应商登录/注册
 */
@Controller
@RequestMapping(value = "/api")
public class SupplyLoginController {
	static final Logger logger = LoggerFactory.getLogger(SurpviseController.class);

	@Autowired
	LoginService loginService;
	@Autowired
	UserMapper supplyUserMapper;
	@Autowired
	RedisUtils redisUtils;
	@Autowired
	SysManageMapper sysManageMapper;
	@Autowired
	SysModuleMapper sysModuleMapper;
	@Autowired
	ModuleDao moduleDao;

	@RequestMapping(value = "/supply/logoff", method = { RequestMethod.POST })
	@ResponseBody
	public HttpResult logoff() {
		SupplyUserModel sysUser = SpringMvcUtils.getSupplyUser();
		redisUtils.del(Global.REDIS_USER_PREFIX + UserTypeEnum.SupplyUser.getValue() + "-" + sysUser.getUserAccout());
		HttpServletRequest httpServletRequest = SpringMvcUtils.getHttpServletRequest();
		httpServletRequest.getSession().invalidate();
		return HttpResult.ok();
	}

	/**
	 * 供应商登录接口
	 *
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/supply/supplierLogin", method = { RequestMethod.POST })
	@ResponseBody
	public HttpResult supplierLogin(@RequestParam String loginName, @RequestParam String pwd) {
		try {
			SupplyUserModel supplyUser = supplyUserMapper.selectSupplyUserByNamePwd(loginName, DesUtils.encrypt(pwd));
			if (supplyUser == null) {
				return HttpResult.error("用户名密码错误！");
			} else {
				HttpResult httpResult = new HttpResult();
				LoginModel loginModel = new LoginModel();
				supplyUser.setUserPwd("");
				loginModel.setSupplyUserModel(supplyUser);
				loginModel.setUserTypeString(UserTypeEnum.SupplyUser.getValue());
				String tokenString = supplyUser.getUserId() + "," + System.currentTimeMillis() + ","
						+ UserTypeEnum.SupplyUser.getValue();
				loginModel.setTokenString(DesUtils.encrypt(tokenString, DesUtils.getKey()));
				httpResult.setData(loginModel);
				redisUtils.set(
						Global.REDIS_USER_PREFIX + UserTypeEnum.SupplyUser.getValue() + "-" + supplyUser.getUserId(),
						supplyUser, Global.PC_BACKGROUND_TOKEN_EXPIRE);
				return httpResult;
			}
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("errorMessage:{}", e.getMessage());
			return HttpResult.error(e.getMessage());
		}
	}

	/**
	 * 供应商注册接口
	 *
	 * @param map
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/supply/supplierRegister", method = { RequestMethod.POST })
	@ResponseBody
	public HttpResult supplierRegister(HttpServletRequest request, @RequestParam Map<String, Object> map)
			throws Exception {
		if (map.isEmpty()) {
			return HttpResult.error(HttpStatus.GLOBAL_EXCEPTION_CODE, "参数不得为空");
		}
		request.getSession().setAttribute("userType", UserTypeEnum.SupplyUser.getValue());
		return loginService.supplierRegister(map);
	}

	@RequestMapping(value = "/supply/selectModuleMap", produces = "text/json;charset=UTF-8")
	@ResponseBody
	public String selectModuleMap() {
		SupplyUserModel supplyUserModel = SpringMvcUtils.getSupplyUser();
		HashMap<String, Object> moduleHashMap = new HashMap<String, Object>();
		moduleHashMap.put("infId", supplyUserModel.getInfId());
		List<ModuleModel> moduleModels = moduleDao.selectList(moduleHashMap);

//		HashMap<String, Object> hashMap = new HashMap<String, Object>();
//		hashMap.put("MODULEID", SysModuleIdEnum.partner.getValue().toString());
		List<SysModule> sysModules = sysModuleMapper.selectAll();

		List<JsonTreeData> treeDataList = new ArrayList<JsonTreeData>();
		for (ModuleModel model : moduleModels) {
			JsonTreeData treeData = new JsonTreeData();
			treeData.setId(model.getModuleId());
			treeData.setPid(model.getModulePid());
			treeData.setText(model.getModuleName());
			Map<String, Object> attributes = new HashMap<String, Object>();
			attributes.put("url", model.getModuleUrl());
			treeData.setAttributes(attributes);
			treeDataList.add(treeData);
		}
		for (SysModule map : sysModules) {
			if (map.getDisabled().equals(Global.NO + "") || map.getShow().equals(Global.NO + "")) {
				continue;
			}
			JsonTreeData treeData = new JsonTreeData();
			treeData.setId(map.getModuleid());
			treeData.setPid(map.getParentmoduleid());
			treeData.setText(map.getModulename());
			Map<String, Object> attributes = new HashMap<String, Object>();
			attributes.put("url", map.getModuleurl());
			treeData.setAttributes(attributes);
			treeDataList.add(treeData);
		}

		List<JsonTreeData> newTreeDataList = EasyuiUtils.getTreeJson(treeDataList,
				SysModuleIdEnum.partner.getValue().toString(), "");
		HttpResult httpResult = new HttpResult();
		httpResult.setRows(newTreeDataList);
//		return httpResult;
		String slist = JSON.toJSONString(newTreeDataList);
		// System.out.println(slist);
		logger.info("treelist测试:{}", slist);
		// request.setAttribute("addLists", list);
		return slist;

	}
}
